package com.xiaocg.json.ongl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;

import java.util.Map;

/**
 * 通过gson 和ognl 表达式，精准json
 *
 */
public class JsonUtil {
    public static <T> T getValue(String json,String text,Class<T> clazz){
        Map<String, Object> map = transferToMap(json);
        OgnlContext context = new OgnlContext();
        context.setRoot(map);
        try {
            T value = (T)Ognl.getValue(text, context, context.getRoot());
            return value;
        } catch (OgnlException e) {
            throw new RuntimeException();
        }
    }

    public static Map<String,Object> transferToMap(String json){
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
    }

    public static void main(String[] args) {
        String json = "{\n" +
                "\t\"userName\": \"meta123\",\n" +
                "\t\"passwd\": \"meta123\",\n" +
                "\t\"xx\": {\n" +
                "\t\t\"cc\": {\n" +
                "\t\t\t\"dd\": \"xxyyzz\"\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";

        String value = getValue(json, "xx.cc.dd", String.class);
        System.out.println(value);
    }
}
